package io.ooad.jenkins.shuren;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import hudson.FilePath;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Created by yyang on 2017/1/3.
 */
public final class Utils {
    public static ShurenyunService createShurenyunService(String url, long timeout) {
        return createRetrofit(url, timeout).create(ShurenyunService.class);
    }

    private static Retrofit createRetrofit(String url, long timeout) {
        return new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(JacksonConverterFactory.create())
                .client(createClient(timeout))
                .build();
    }

    private static OkHttpClient createClient(long timeout) {
        return new OkHttpClient.Builder()
                .addInterceptor(new AuthInterceptor())
                .connectTimeout(timeout, TimeUnit.MILLISECONDS)
                .build();
    }

    public static JsonNode createLoginInfo(String username, String password) {
        ObjectNode loginInfo = new ObjectMapper().createObjectNode();
        loginInfo.set("userName", new TextNode(username));
        loginInfo.set("password", new TextNode(password));
        return loginInfo;
    }

    public static JsonNode readAppDefinition(FilePath filePath) {
        JsonNode appInfo = null;
        try {
            return new ObjectMapper().readTree(readFile(filePath));
        } catch (IOException e) {
            throw new RuntimeException("应用信息格式错误");
        }

    }

    private static String readFile(FilePath filePath) {
        try {
            if (!filePath.exists()) {
                throw new RuntimeException("文件不存在");
            }
            return new String(filePath.readToString());
        } catch (IOException e) {
            throw new RuntimeException("无法读取文件");
        } catch (InterruptedException e) {
            throw new RuntimeException("无法读取文件");
        }
    }
}
